package com.lightjet.macross.base.upms.controller;

import com.lightjet.macross.base.feign.api.controller.PrincipalController;
import com.lightjet.macross.base.feign.api.domain.AuthUser;
import com.lightjet.macross.base.upms.domain.ResourceInfo;
import com.lightjet.macross.base.upms.domain.SystemInfo;
import com.lightjet.macross.base.upms.dto.AdminLTEMenuDTO;
import com.lightjet.macross.base.upms.dto.D2AdminMenuDTO;
import com.lightjet.macross.base.upms.service.ResourceInfoService;
import com.lightjet.macross.base.upms.service.RoleResourceLinkService;
import com.lightjet.macross.base.upms.service.SystemInfoService;
import com.lightjet.macross.common.dto.ResponseDTO;
import com.lightjet.macross.common.util.RespUtil;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.*;
import lombok.extern.java.Log;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/resource")
@Scope("request")
@Log
@Api(tags="通用系统权限管理-资源相关接口集")
public class ResourceController extends PrincipalController  { //implements ResourceRemoteClient

    @Resource
    private ResourceInfoService resourceInfoService;

    @Resource
    private SystemInfoService systemInfoService;

    @Resource
    private RoleResourceLinkService roleResourceLinkService;

    @GetMapping("/mine")
    @ApiOperation(value = "用户访问资源接口", notes = "用于查询某系统下某用户的所有可访问资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userkey",value = "用户唯一标识，如为空则取Token内用户key信息",paramType = "query"),
            @ApiImplicitParam(name="systemshortname",value = "系统简称",paramType = "query")
    })
    //@Override
    public ResponseDTO<List<ResourceInfo>> GetResourceByUserAndSystem(String userkey, String systemshortname,@ApiIgnore @ModelAttribute("CurrentUser") AuthUser user) {
        return RespUtil.CreateOK(resourceInfoService.GetUserResourceCollection(StringUtil.isNullOrEmpty(userkey)?user.getId():userkey,systemshortname));
    }

    @GetMapping("/minelte")
    @ApiOperation(value = "用户访问资源接口", notes = "用于查询某系统下某用户的所有可访问资源并返回适用于AdminLTE前端的菜单Json")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userkey",value = "用户唯一标识，如为空则取Token内用户key信息",paramType = "query"),
            @ApiImplicitParam(name="systemshortname",value = "系统简称",paramType = "query")
    })
    //@Override
    public ResponseDTO<List<AdminLTEMenuDTO>> GetResourceTreeByUserAndSystem(String userkey, String systemshortname,@ApiIgnore @ModelAttribute("CurrentUser") AuthUser user)
    {
        List<ResourceInfo> list = resourceInfoService.GetUserResourceCollection(StringUtil.isNullOrEmpty(userkey)?user.getId():userkey,systemshortname);
        return RespUtil.CreateOK(ConvertToAdminLTEJson(list,-1));
    }

    private List<AdminLTEMenuDTO> ConvertToAdminLTEJson(List<ResourceInfo> sourceList,Integer parentId)
    {
        List<AdminLTEMenuDTO> targetList = new ArrayList<>();
        List<ResourceInfo> lists = sourceList.stream().filter(e-> e.getParent().getId().equals(parentId)).collect(Collectors.toList());
        for(ResourceInfo resourceInfo : lists)
        {
            AdminLTEMenuDTO adminLTEMenuDTO = new AdminLTEMenuDTO();
            adminLTEMenuDTO.setIcon(resourceInfo.getIcno());
            adminLTEMenuDTO.setId(resourceInfo.getId().toString());
            adminLTEMenuDTO.setText(resourceInfo.getResourcename());
            adminLTEMenuDTO.setUrl(resourceInfo.getUri());
            adminLTEMenuDTO.setChildren(ConvertToAdminLTEJson(sourceList,resourceInfo.getId()));
            adminLTEMenuDTO.setMemo(resourceInfo.getArgument2());
            if(resourceInfo.getResourcetype().equals(0))
            {
                adminLTEMenuDTO.setTargetType("iframe-tab");
            }
            targetList.add(adminLTEMenuDTO);
        }
        return targetList;
    }

    private List<D2AdminMenuDTO> ConvertToD2AdminJson(List<ResourceInfo> sourceList,Integer parengId)
    {
        //ResourceInfo reourceRoot = sourceList.stream().filter(e->e.getResourcetype().equals(ResourceInfo.ResourceTypeEnum.MENU) && e.getResourcename().equals(rootname)).findFirst().orElse(null);
        List<ResourceInfo> rawList = sourceList.stream()
                .filter(e->e.getResourcetype().equals(ResourceInfo.ResourceTypeEnum.MENU) && parengId.equals(e.getParentid()))
                .sorted(Comparator.comparing(ResourceInfo::getOrderno))
                .collect(Collectors.toList());
        List<D2AdminMenuDTO> convertedList = new ArrayList<>();
        for(ResourceInfo resourceInfo : rawList)
        {
            D2AdminMenuDTO d2Node = new D2AdminMenuDTO();
            d2Node.setTitle(resourceInfo.getResourcename());
            d2Node.setIcon(resourceInfo.getIcno());
            d2Node.setHidden(resourceInfo.getHide()==1);
            d2Node.setId(resourceInfo.getId()==null?"":resourceInfo.getId().toString());
            if(!StringUtil.isNullOrEmpty(resourceInfo.getUri()) && !resourceInfo.getUri().equals("#"))
            {
                d2Node.setPath(resourceInfo.getUri());
            }
            List<D2AdminMenuDTO> childNodes = ConvertToD2AdminJson(sourceList,resourceInfo.getId());
            if(childNodes!=null && childNodes.size()>0)
            {
                d2Node.setChildren(childNodes);
            }
            convertedList.add(d2Node);
        }
        return convertedList ;
    }



    @GetMapping("/mined2")
    public ResponseDTO<List<D2AdminMenuDTO>> GetMyResource(String userkey, String systemshortname,String root, @ApiIgnore @ModelAttribute("CurrentUser") AuthUser user) {
        userkey = StringUtil.isNullOrEmpty(userkey)?user.getId():userkey;
        String rootFinal = StringUtil.isNullOrEmpty(root)?"侧栏菜单根目录":root;
        List<ResourceInfo> list = resourceInfoService.GetUserResourceCollection(userkey,systemshortname);
        ResourceInfo rootResource = list.stream().filter(e->e.getResourcename().equals(rootFinal)).findFirst().orElse(null);
        if(rootResource!=null)
        {
            return RespUtil.CreateOK(ConvertToD2AdminJson(list,rootResource.getId()));
        }
        else
        {
            return RespUtil.CreateError(MessageFormat.format("用户【{0}】的{1}菜单权限不存在",userkey,rootFinal));
        }
        /*D2AdminMenuDTO dir = new D2AdminMenuDTO();
        dir.setTitle("接口管理");
        dir.setIcon("cog");
        dir.setId("11");
        D2AdminMenuDTO page1 = new D2AdminMenuDTO();
        page1.setTitle("接口查询");
        page1.setPath("interface/query");
        page1.setIcon("file-o");
        page1.setId("111");
        //page1.setChildren(new ArrayList<>());
        dir.setChildren(Collections.singletonList(page1));
        return RespUtil.CreateOK(Collections.singletonList((dir)));*/
    }

    @PostMapping("/check")
    public ResponseDTO<String> CheckAccess(
            @ApiParam(name = "resurl", value = "待校验的资源路径", required = true) String resurl,
            @ApiParam(name = "systemid", value = "所属系统ID", required = true) String systemid,
            @ApiIgnore @ModelAttribute("CurrentUser") AuthUser user)
    {
        //具体校验暂省略，后面填坑！！！！！！！！！！！！！！！！！！！！
        return RespUtil.CreateOK("成功");
    }

    @GetMapping("/query")
    @ApiOperation(value = "租户系统资源查询接口", notes = "根据租户系统简称及父级资源ID（为空查根节点）查询树状结构的资源集合")
    public ResponseDTO<List<ResourceInfo>> GetBySystemAndParent(
            @ApiParam(name = "systemshortname", value = "系统简称", required = true) String systemshortname,
            @ApiParam(name = "parentid", value = "父节点ID") Integer parentid)
    {
        SystemInfo systemInfo = systemInfoService.FindByShortname(systemshortname);
        if(systemInfo==null)
        {
            return RespUtil.CreateError("系统【"+systemshortname+"】不存在");
        }
        if(parentid == null)
        {
            return RespUtil.CreateOK(resourceInfoService.FindAllByParentAndBelongsystem(null,systemInfo));
        }
        else
        {
            return RespUtil.CreateOK(resourceInfoService.FindAllByParentAndBelongsystem(new ResourceInfo(parentid),systemInfo));
        }
    }

    @PostMapping(value ="",consumes = "application/json")
    @ApiOperation(value = "资源新增接口", notes = "根据资源实体对象Json新增")
    public ResponseDTO<ResourceInfo> CreateRole(
            @ApiParam(name = "resourceInfo",value = "资源实体类Json",type="body")@RequestBody ResourceInfo resourceInfo){
        if(resourceInfo.getParent()!=null && resourceInfo.getParent().getId() == null)
        {
            resourceInfo.setParent(null);
        }
        return RespUtil.CreateOK(resourceInfoService.CreateAndFlush(resourceInfo));

    }

    @PutMapping(value ="",consumes = "application/json")
    @ApiOperation(value = "资源更新接口", notes = "根据资源实体对象Json更新")
    public ResponseDTO<ResourceInfo> UpdateRole(
            @ApiParam(name = "resourceInfo",value = "资源实体类Json",type="body")@RequestBody ResourceInfo resourceInfo){
        ResourceInfo original = resourceInfoService.FindDistinctById(resourceInfo.getId());
        if(original == null)
        {
            return RespUtil.CreateError("更新资源【"+resourceInfo.getId()+"】失败");
        }
        else
        {
            original.setOrderno(resourceInfo.getOrderno());
            original.setUri(resourceInfo.getUri());
            original.setResourcetype(resourceInfo.getResourcetype());
            original.setEnabled(resourceInfo.getEnabled());
            original.setResourcename(resourceInfo.getResourcename());
            original.setIcno(resourceInfo.getIcno());
            original.setHide(resourceInfo.getHide());
            original.setRemark(resourceInfo.getRemark());
            roleResourceLinkService.ClearCache();
            return RespUtil.CreateOK(resourceInfoService.UpdateAndFlush(original));
        }
    }

    @DeleteMapping(value = "")
    @ApiOperation(value = "资源删除接口", notes = "根据资源ID删除")
    public ResponseDTO<String> DeleteRole( @ApiParam(name = "id",value = "资源ID",type="query") Integer id){
        try {
            resourceInfoService.DeleteOne(new ResourceInfo(id));
            return RespUtil.CreateOK();
        }
        catch (Exception e)
        {
            return RespUtil.CreateError("删除失败："+e.getMessage());
        }
    }
/*    public ResponseDTO<List<D2AdminRouteDTO>> GetMyResource(String userkey, String systemshortname,@ApiIgnore @ModelAttribute("CurrentUser") AuthUser user)
    {
        D2AdminRouteDTO dir = new D2AdminRouteDTO();
        dir.setName("interface");
        dir.setPath("interface");
        dir.setMeta(new D2AdminMenuMetaDTO("接口管理",false,""));
        D2AdminRouteDTO page1 = new D2AdminRouteDTO();
        page1.setName("interface_query");
        page1.setPath("interface/query");
        page1.setMeta(new D2AdminMenuMetaDTO("接口查询",false,""));
        page1.setComponent("interface/query");
        dir.setChildren(Collections.singletonList(page1));

        return RespUtil.CreateOK(Collections.singletonList((dir)));
    }*/
}
